<?php
  
  session_start();

  $error = 0;
  $message = "";
  
  require_once 'TemplateGenerator.php';

  if ($_FILES['file']['error'] > 0)
  {
    $message = "Keine Datei angegeben";
    $error = 1;
  }
  require_once('config.inc.php');
  require('DatabaseManager.php');

  $db = new DatabaseManager;
  $db -> createDB();

  $file_name = $_FILES['file']['name'];
  $tmp_file = $_FILES['file']['tmp_name'];
  
  $template_name = basename($file_name,".zip");
  
  $template_gen = new TemplateGenerator();
  if (!$template_gen->isValidZip($tmp_file, $file_name))
  {
    $message = "Keine Zip Datei.";
    $error = 1;
  }
  
  if ($error == 0)
  {
    $category_id = $_SESSION['category_id'];
	$query1 = "SELECT * FROM files WHERE template_name = '$template_name' AND category_id = '$category_id'";
	$result1 = MYSQL_QUERY($query1);
	$num_rows =  mysql_num_rows($result1);
    
	if (!$num_rows)
	{
      $query2 = "INSERT INTO files VALUES('NULL', '$template_name', '".$category_id."', '')";
      $result2 = MYSQL_QUERY($query2);
      
      if (!$result2)
      {
        $message = "Fehler in der Datenbank";
        $error = 1;
      }
      
      $template_id = mysql_insert_id();
      
      $user_template_dir = dirname(__FILE__)."/../users/".$_SESSION['user_id']."/templates/".$_SESSION['category_id']."/";
      $template_gen->createTemplate($_FILES['file']['tmp_name'],$template_name,$user_template_dir);
      
      $message = "Template hinzugef&uuml;gt";
	}
	else
	{
        $message = "Template bereits vorhanden";
        $error = 1;
	}
	

  }
  
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Template hinzuf&uuml;gen</title>
</head>
<body>
<div><?php echo $message; ?></div>
<div><a href="index.php?action=category_choosen">OK</a></div>
</body>
</html>




